package com.cbgolf.oa.views;

import android.app.Activity;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.base.BaseViewNew;
import com.cbgolf.oa.contract.IMainContract.IMainView;
import com.cbgolf.oa.contract.IMainContract.IMainWaiter;
import com.cbgolf.oa.entity.MenuBean;
import com.cbgolf.oa.entity.Menus;
import com.cbgolf.oa.entity.RolesBean;
import com.cbgolf.oa.event.EventMenus;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DialogUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.StatusBarUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.CircleImageView;
import com.cbgolf.oa.widget.GridViewNew;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.abslistview.CommonAdapter;
import java.util.ArrayList;
import java.util.List;
import org.xutils.view.annotation.ViewInject;

/**
 *
 * @author lq
 * @date 2017/11/3
 */
public class MainViewImp extends BaseViewNew implements IMainView {

  @ViewInject(R.id.g_toolbar_left_ll)
  private View topLeftView;
  @ViewInject(R.id.g_toolbar_title_tv)
  private TextView titleTv;
  @ViewInject(R.id.rl_main_topright)
  private View topRight;
  @ViewInject(R.id.iv_main_redpoint)
  private ImageView redPointIv;
  @ViewInject(R.id.iv_main_qrcode)
  private ImageView qrCodeIv;
  //drawer
  @ViewInject(R.id.drawer_layout)
  private DrawerLayout drawerLayout;
  //left
  @ViewInject(R.id.g_left_header_civ)
  private CircleImageView headerCiv;
  @ViewInject(R.id.g_left_name_tv)
  private TextView nameTv;
  @ViewInject(R.id.g_left_job_tv)
  private TextView jobTv;
  @ViewInject(R.id.g_left_pwd_modify_tv)
  private TextView pwdModiTv;
  @ViewInject(R.id.g_left_quit_tv)
  private TextView quitTv;
  //main
  @ViewInject(R.id.main_listview)
  private ListView listView;
  @ViewInject(R.id.main_data_ll)
  private View dataView;

  private ErrorView errorView;
  private CommonAdapter<MenuBean> adapter;
  private IMainWaiter worker;

  public MainViewImp(Activity act, IMainWaiter worker) {
    this.worker = worker;
    ViewUtils.autoInjectAllField(this, act);
    super.init(act);
  }

  @Override
  protected void findViews() {
    errorView = new ErrorView(context);
    errorView.setLogoVisible(false);
  }

  @Override
  protected void setViews() {
    StatusBarUtil.setTranslucentForDrawerLayout(context, drawerLayout, 0);
    ViewUtils.setVisible(qrCodeIv, false);
//        setSupportActionBar(mToolbar);
//        mToolbar.setBackgroundColor(getResources().getColor(android.R.color.transparent));
//        去除左右抽屉划出后内容显示页背景的灰色？
//        drawerLayout.setScrimColor(Color.TRANSPARENT);
//        如何填充抽屉的划出后与屏幕边缘之间的内容（即上面的灰色部分）？
//        drawerLayout.setDrawerShadow(Drawable shadowDrawable, int gravity)
//        drawerLayout.setDrawerShadow(int resId, int gravity)
//        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, mToolbar, R.string.navigation_drawer_open,
//                R.string.navigation_drawer_close);
//        drawerLayout.setDrawerListener(toggle);
//        toggle.syncState();
//        StatusBarUtil.setColorForDrawerLayout(MainActivity.this, mDrawerLayout, mStatusBarColor, mAlpha);
    adapter = new CommonAdapter<MenuBean>(context, R.layout.item_main_menu, listData) {
      @Override
      public void convert(ViewHolder holder, MenuBean menuDataBean) {
        if (null == menuDataBean) {
          return;
        }
        holder.setText(R.id.item_main_title_tv, TextUtil.Text(menuDataBean.typeName));
        if (!Util.listIsNull(menuDataBean.list)) {
          setGridAdapter(holder.getView(R.id.item_main_gridview), menuDataBean.list);
        }
      }
    };
    listView.setAdapter(adapter);

  }

  private void setGridAdapter(GridViewNew gridView, List<Menus> list) {
    if (Util.listIsNull(list)) {
      return;
    }
    CommonAdapter<Menus> adapter = new CommonAdapter<Menus>(context,
        R.layout.item_menu, list) {
      @Override
      public void convert(final ViewHolder holder, final Menus bean) {
        if (null == bean) {
          return;
        }
        for (int i = 0; i < DataManager.MUNE_TITLES.length; i++) {
          if (TextUtil.contains(bean.modelId, DataManager.MUNE_IDS[i])) {
            holder.setImageResource(R.id.item_menu_iv, DataManager.MUNE_ICONS[i])
                .setText(R.id.item_menu_tv, TextUtil.Text(DataManager.MUNE_TITLES[i]));
            break;
          }
        }
        holder.setOnClickListener(R.id.item_menu_ll, v -> {
          for (int i = 0; i < DataManager.MUNE_TITLES.length; i++) {
            if (TextUtil.contains(bean.modelId, DataManager.MUNE_IDS[i])) {
              worker.onClickMenu(i);
              break;
            }
          }
        });

      }
    };
    gridView.setAdapter(adapter);
  }


  @Override
  protected void setListener() {
    ViewUtils.setClick(topLeftView, v -> {
      if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) {
        drawerLayout.openDrawer(Gravity.LEFT);
      }
    });
    ViewUtils.setClick(pwdModiTv, v -> {
      if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
        drawerLayout.closeDrawer(Gravity.LEFT);
      }
      worker.onClickModifyPwd();
    });
    ViewUtils.setClick(quitTv, v -> {
      if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
        drawerLayout.closeDrawer(Gravity.LEFT);
      }
      DialogUtil.showQuitDialog(context, () -> worker.quitOA());
    });
    ViewUtils.setClick(topRight, v -> {
      worker.onClickMsg();
    });
    ViewUtils.setClick(qrCodeIv, v -> {
      worker.onClickQrCode();
    });
  }


  private List<MenuBean> listData = new ArrayList<>();


  @Override
  public void requestOver(EventMenus event) {
    if (null == event) {
      return;
    }
    switch (event.target) {
      case DataManager.MENUS_MAIN:
        stopProgress();
        ViewUtils.setVisible(qrCodeIv, event.hasOrderConfirmPermission);
        errorView.showData(dataView);
        if (!Util.listIsNull(event.listMenus)) {
          listData.clear();
          listData.addAll(event.listMenus);
          adapter.notifyDataSetChanged();
        } else if (Util.listIsNull(listData)) {
          requestFail(Util.isNull(event.errorMsg) ? ErrorUtil.NODATA : event.errorMsg,
              event.errorCode);
        }
        break;
      case DataManager.USER_INFO_REFRESH:
        refreshUserInfo();
        break;
      case DataManager.ORDER_CONFIRM_BYQR:
        stopProgress();
        if (event.isConfirmSuccess) {
          Util.show("验证成功");
          if (null != event.orderBean) {
            worker.showOrderDetails(event.orderBean);
          }
        } else {
          DialogUtil.showIKnowDialog(context,
              "温馨提示",
              Util.isNull(event.errorMsg) ? "很抱歉,订单验证异常" : event.errorMsg);
        }
        break;
      case DataManager.MESSAGE_NO_READ:
        ViewUtils.setVisible(redPointIv, event.haveNotRead);
        break;
      default:
        break;
    }

  }

  public void refreshUserInfo() {
    ViewUtils.setText(titleTv, worker.getActivityTitle());
    ViewUtils.setText(nameTv, DataUtil.getUserName());
    List<RolesBean> list = DataUtil.getListArray(DataUtil.getRoles(), RolesBean.class);
    if (!Util.listIsNull(list)) {
      jobTv.setText(TextUtil.Text(list.get(0).name));
    }
    CrashReport.setUserId(DataUtil.getUserAccount());
  }


  @Override
  public void requestFail(String msg, int code) {
    if (null != errorView) {
      errorView.showError(dataView, msg, code, () -> worker.reload());
    }
  }


  @Override
  public void showProgress() {
    if (Util.listIsNull(listData)) {
      errorView.showLoading(dataView, true);
    }
  }

  @Override
  public void stopProgress() {
    if (null != errorView) {
      errorView.stopLoading();
    } else {
      AnimaUtil.stopLoading();
    }
  }

}
